package com.frxuexi.video.view

import android.media.tv.TvView
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.frxuexi.lib_base.entity.FocuseBean
import com.frxuexi.lib_base.entity.FocuseBeanItem
import com.frxuexi.lib_base.entity.VideoBeanItem
import com.frxuexi.lib_base.entity.VideoCommentBeanItem
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseFragment
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.room.ZanEntity
import com.frxuexi.lib_base.utils.DateTimeUtils
import com.frxuexi.video.R
import com.frxuexi.video.adapter.VideoAdapter
import com.frxuexi.video.VideoIntent
import com.frxuexi.video.VideoViewModel
import com.frxuexi.video.adapter.CommentAdapter
import com.frxuexi.video.databinding.FragmentVideoBinding
import com.frxuexi.video.databinding.PopCommentBinding
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding, VideoIntent, VideoViewModel>() {
    override val binding: FragmentVideoBinding by lazy { FragmentVideoBinding.inflate(layoutInflater) }
    override val vm: VideoViewModel by viewModels<VideoViewModel>()
    val videoAdapter by lazy { VideoAdapter() }
    var position = 0
    var flag = false
    var items= mutableListOf<VideoCommentBeanItem>()

    val commentAdapter by lazy { CommentAdapter() }
    lateinit var pop: PopCommentBinding

    lateinit var commentBeanItem: VideoCommentBeanItem

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                val items = it.data as List<VideoBeanItem>
                                videoAdapter.addData(items)
                                videoAdapter.notifyDataSetChanged()
                            }

                            RequestType.SELECT_ITEM -> {
                                flag = true
                                val iv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.iv_love
                                ) as ImageView
                                iv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_action_love)
                                val tv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.tv_love
                                ) as TextView
                                tv.setText("1")
                            }

                            RequestType.ADD -> {
                                flag = true
                                val iv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.iv_love
                                ) as ImageView
                                iv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_action_love)
                                val tv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.tv_love
                                ) as TextView
                                tv.setText("1")
                            }

                            RequestType.DELETE -> {
                                flag = false
                                val iv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.iv_love
                                ) as ImageView
                                iv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_xihuan)
                                val tv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.tv_love
                                ) as TextView
                                tv.setText("0")
                            }

                            RequestType.COMMENTS -> {
                                items.clear()
                                items.addAll(it.data as List<VideoCommentBeanItem>)
                                val tv = videoAdapter.getViewByPosition(
                                    position,
                                    R.id.tv_comment
                                ) as TextView
                                tv.setText("${items.size}")
                                commentAdapter.data.clear()
                                commentAdapter.addData(items)
                                commentAdapter.notifyDataSetChanged()
                            }
                            RequestType.ADD_COMMENT->{
                                commentAdapter.data.add(0,commentBeanItem)
                                commentAdapter.notifyItemInserted(0)
                                pop.et.setText("")
                            }
                            RequestType.GET_FOCUSE->{
                                val beans = it.data as List<FocuseBeanItem>
                                if(beans.filter {it.nick==videoAdapter.data.get(position).name}.size>0){
                                    val iv = videoAdapter.getViewByPosition(
                                        position,
                                        R.id.iv_add
                                    ) as ImageView
                                    iv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_action_ok)
                                }
                            }
                            RequestType.ADD_FOCUSE->{

                            }
                            RequestType.DELETE_FOCUSE->{

                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        val layout = LinearLayoutManager(requireContext())
        binding.videoRv.apply {
            adapter = videoAdapter
            layoutManager = layout
        }
        vm.sendIntent(VideoIntent.getVideos(0))

        //仿真翻页
        PagerSnapHelper().attachToRecyclerView(binding.videoRv)



        //滚动自动播放
        binding.videoRv.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            flag = false
            position = layout.findFirstVisibleItemPosition()
            val gsy =
                videoAdapter.getViewByPosition(position, R.id.gsy) as StandardGSYVideoPlayer
            gsy.startPlayLogic()
            vm.sendIntent(VideoIntent.isZan(videoAdapter.data[position].id))
            vm.sendIntent(VideoIntent.getComments(videoAdapter.data[position].id))
            vm.sendIntent(VideoIntent.getFocuse("lr"))
        }

        videoAdapter.addChildClickViewIds(R.id.iv_love,R.id.iv_comment)
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.iv_love->{
                    val zanEntity = ZanEntity(videoAdapter.data[position].id)
                    if (flag) {
                        vm.sendIntent(VideoIntent.cancelZan(zanEntity))
                    } else {
                        vm.sendIntent(VideoIntent.addZan(zanEntity))
                    }
                    flag = !flag
                }
                R.id.iv_comment->{

                    val window = PopupWindow(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        1000
                    )
                    window.isFocusable=true
                    pop= PopCommentBinding.inflate(LayoutInflater.from(requireContext()))
                    window.contentView=pop.root
                    window.showAtLocation(view,Gravity.BOTTOM,0,0)

                    pop.etcount.setText("评论数量:${items.size}")
                    pop.colose.setOnClickListener {
                        window.dismiss()
                    }


                    pop.rvComment.apply {
                        this.adapter=commentAdapter
                        layoutManager=LinearLayoutManager(requireContext())
                    }

                    pop.fasong.setOnClickListener {
                        val itemId = videoAdapter.data.get(position).item_id
                        val content = pop.et.text.toString()
                        commentBeanItem = VideoCommentBeanItem(
                            0, content, DateTimeUtils.getDateTime(System.currentTimeMillis()),
                            0, null, itemId, "lr", emptyList(), 0, 0, ""
                        )
                        vm.sendIntent(VideoIntent.addComment(commentBeanItem))
                    }
                }
            }

        }

    }

}